package com.my.blog.website.controller.admin;

import com.github.pagehelper.PageInfo;
import com.my.blog.website.controller.BaseController;
import com.my.blog.website.dto.LogActions;
import com.my.blog.website.modal.Bo.RestResponseBo;
import com.my.blog.website.modal.Vo.UserVo;
import com.my.blog.website.service.ILogService;
import com.my.blog.website.service.IUserService;
import com.my.blog.website.utils.GsonUtils;
import com.my.blog.website.utils.TaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by wangq on 2017/3/20.
 */
@Controller
@RequestMapping("admin/users")
public class UserController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService usersService;

    @Resource
    private ILogService logService;

    /**
     * 新增用户
     */
    @PostMapping(value = "save")
    @ResponseBody
    public RestResponseBo save(UserVo userVo,
                               HttpServletRequest request) {
        try {
            usersService.insertUser(userVo);

            logService.insertLog(LogActions.ADD_USER.getAction(), GsonUtils.toJsonString(userVo), request.getRemoteAddr(), this.getUid(request));
            return RestResponseBo.ok();
        } catch (Exception e) {
            String msg = "新增用户失败";
            return RestResponseBo.fail(msg);
        }
    }

    @GetMapping(value = "new")
    public String newUser(HttpServletRequest request) {
        return "admin/user_edit";
    }

    /**
     * 修改用户
     *
     * @param uid
     * @param request
     * @return
     */
    @GetMapping(value = "{uid}")
    public String editUser(@PathVariable Integer uid, HttpServletRequest request) {
        UserVo userVo = usersService.queryUserById(uid);
        request.setAttribute("user", userVo);

        request.setAttribute("active", "user");
        return "admin/user_edit";
    }

    /**
     * 修改用户
     *
     * @param userVo
     * @param request
     * @return
     */
    @PostMapping(value = "modify")
    @ResponseBody
    public RestResponseBo modifyUser(UserVo userVo, HttpServletRequest request) {
        String username = userVo.getUsername();
        String pwd = userVo.getPassword();
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(pwd)){
            String encodePassword = TaleUtils.MD5encode(username + pwd);
            userVo.setPassword(encodePassword);
        }else {
            userVo.setPassword(null);
        }
        int result = usersService.updateByUid(userVo);
        if (result == 0) {
            return RestResponseBo.fail(result);
        }
        return RestResponseBo.ok();
    }

    /**
     * 修改用户的激活状态
     */
    @PostMapping(value = "chageActivate")
    @ResponseBody
    public RestResponseBo chageActivate(
                               @RequestParam(required = true) Integer uid,
                               @RequestParam(required = false,defaultValue = "1") Integer activated,
                               HttpServletRequest request) {
        try {
            UserVo userVo = new UserVo();
            userVo.setUid(uid);
            /*if (StringUtils.isNotBlank(userName))userVo.setUsername(userName);
            if (StringUtils.isNotBlank(passWord))userVo.setPassword(passWord);
            if (StringUtils.isNotBlank(email))userVo.setEmail(email);
            if (StringUtils.isNotBlank(screenName))userVo.setScreenName(screenName);
            if (StringUtils.isNotBlank(groupName))userVo.setGroupName(groupName);*/

            userVo.setActivated(activated);//是否激活 1：激活，0：不激活

            usersService.updateByUid(userVo);

            logService.insertLog(LogActions.UPDATE_USER.getAction(), GsonUtils.toJsonString(userVo), request.getRemoteAddr(), this.getUid(request));
            return RestResponseBo.ok();
        } catch (Exception e) {
            String msg = "修改用户失败";
            return RestResponseBo.fail(msg);
        }
    }

    /**
     * 查询用户列表
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping(value = "")
    public String list(@RequestParam(value = "page", defaultValue = "1") int page,
                         @RequestParam(value = "limit", defaultValue = "15") int limit,
                         @RequestParam(value = "userName",required = false) String userName,
                       HttpServletRequest request) {

        PageInfo<UserVo> usersPaginator = usersService.queryListWithPage(page, limit,userName);

        request.setAttribute("users", usersPaginator);
        request.setAttribute("userName",userName);
        return "admin/user_list";
    }

}
